// pages/final-answer/index.js
const app = getApp()
const themeManager = require('../../utils/theme-manager')
const { storage } = require('../../utils/storage')
const api = require('../../services/api')

Page({
  data: {
    // 主题相关
    theme: 'gold',
    isDarkMode: false,
    
    // 页面状态
    loading: false,
    currentView: 'home', // home, create, unlock, history, detail
    
    // 答案锁数据
    answerLocks: [],
    currentLock: null,
    
    // 创建答案锁
    createForm: {
      question: '',
      answer: '',
      hint: '',
      difficulty: 'medium', // easy, medium, hard
      category: 'personal', // personal, relationship, future, fun
      isPrivate: false,
      unlockCondition: 'correct_answer' // correct_answer, time_based, mutual_unlock
    },
    
    // 解锁相关
    unlockForm: {
      userAnswer: '',
      attempts: 0,
      maxAttempts: 3,
      showHint: false,
      isUnlocked: false
    },
    
    // 统计数据
    stats: {
      totalCreated: 0,
      totalUnlocked: 0,
      successRate: 0,
      favoriteCategory: '',
      streakDays: 0
    },
    
    // UI状态
    showCreateModal: false,
    showUnlockModal: false,
    showStatsModal: false,
    showDetailModal: false,
    showSettingsModal: false,
    
    // 设置
    settings: {
      enableNotifications: true,
      autoSaveProgress: true,
      showDifficulty: true,
      enableHints: true,
      soundEffects: true
    },
    
    // 分类和难度选项
    categories: [
      { id: 'personal', name: '个人成长', icon: '🌱', color: '#4CAF50' },
      { id: 'relationship', name: '感情关系', icon: '💕', color: '#E91E63' },
      { id: 'future', name: '未来规划', icon: '🌟', color: '#2196F3' },
      { id: 'fun', name: '趣味问答', icon: '🎉', color: '#FF9800' }
    ],
    
    difficulties: [
      { id: 'easy', name: '简单', color: '#4CAF50', description: '轻松回答' },
      { id: 'medium', name: '中等', color: '#FF9800', description: '需要思考' },
      { id: 'hard', name: '困难', color: '#F44336', description: '深度挖掘' }
    ],
    
    // 过滤和排序
    filterOptions: {
      category: 'all',
      difficulty: 'all',
      status: 'all', // all, locked, unlocked
      sortBy: 'created_time' // created_time, difficulty, category
    }
  },

  onLoad(options) {
    this.initTheme()
    this.loadSettings()
    this.loadAnswerLocks()
    this.loadStats()
    
    // 处理分享进入
    if (options.lockId) {
      this.openLockDetail(options.lockId)
    }
  },

  onUnload() {
    // 清理定时器
    if (this.saveTimer) {
      clearTimeout(this.saveTimer)
    }
  },

  // 初始化主题
  initTheme() {
    const theme = themeManager.getCurrentTheme()
    const isDarkMode = themeManager.isDarkMode()
    this.setData({ theme, isDarkMode })
  },

  // 加载设置
  loadSettings() {
    // 修复：正确访问存储对象
    const settings = storage.get('final_answer_settings') || this.data.settings
    this.setData({ settings })
  },

  // 加载答案锁列表
  async loadAnswerLocks() {
    try {
      this.setData({ loading: true })
      
      const locks = storage.get('answer_locks') || []
      const filteredLocks = this.filterLocks(locks)
      
      this.setData({ 
        answerLocks: filteredLocks,
        loading: false 
      })
    } catch (error) {
      console.error('加载答案锁失败:', error)
      this.setData({ loading: false })
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      })
    }
  },

  // 过滤答案锁
  filterLocks(locks) {
    const { category, difficulty, status, sortBy } = this.data.filterOptions
    
    let filtered = locks.filter(lock => {
      if (category !== 'all' && lock.category !== category) return false
      if (difficulty !== 'all' && lock.difficulty !== difficulty) return false
      if (status !== 'all') {
        if (status === 'locked' && lock.isUnlocked) return false
        if (status === 'unlocked' && !lock.isUnlocked) return false
      }
      return true
    })
    
    // 排序
    filtered.sort((a, b) => {
      switch (sortBy) {
        case 'created_time':
          return new Date(b.createdAt) - new Date(a.createdAt)
        case 'difficulty':
          const difficultyOrder = { easy: 1, medium: 2, hard: 3 }
          return difficultyOrder[a.difficulty] - difficultyOrder[b.difficulty]
        case 'category':
          return a.category.localeCompare(b.category)
        default:
          return 0
      }
    })
    
    return filtered
  },

  // 加载统计数据
  loadStats() {
    const locks = storage.get('answer_locks') || []
    const unlockedLocks = locks.filter(lock => lock.isUnlocked)
    
    const stats = {
      totalCreated: locks.length,
      totalUnlocked: unlockedLocks.length,
      successRate: locks.length > 0 ? Math.round((unlockedLocks.length / locks.length) * 100) : 0,
      favoriteCategory: this.getFavoriteCategory(locks),
      streakDays: this.calculateStreakDays(locks)
    }
    
    this.setData({ stats })
  },

  // 获取最喜欢的分类
  getFavoriteCategory(locks) {
    const categoryCount = {}
    locks.forEach(lock => {
      categoryCount[lock.category] = (categoryCount[lock.category] || 0) + 1
    })
    
    let maxCount = 0
    let favoriteCategory = ''
    Object.entries(categoryCount).forEach(([category, count]) => {
      if (count > maxCount) {
        maxCount = count
        favoriteCategory = category
      }
    })
    
    const categoryInfo = this.data.categories.find(cat => cat.id === favoriteCategory)
    return categoryInfo ? categoryInfo.name : '暂无'
  },

  // 计算连续天数
  calculateStreakDays(locks) {
    if (locks.length === 0) return 0
    
    const today = new Date()
    const oneDayMs = 24 * 60 * 60 * 1000
    let streak = 0
    
    for (let i = 0; i < 30; i++) {
      const checkDate = new Date(today.getTime() - i * oneDayMs)
      const dateStr = checkDate.toDateString()
      
      const hasActivity = locks.some(lock => {
        const lockDate = new Date(lock.createdAt).toDateString()
        const unlockDate = lock.unlockedAt ? new Date(lock.unlockedAt).toDateString() : null
        return lockDate === dateStr || unlockDate === dateStr
      })
      
      if (hasActivity) {
        streak++
      } else if (i > 0) {
        break
      }
    }
    
    return streak
  },

  // 切换视图
  onSwitchView(e) {
    const { view } = e.currentTarget.dataset
    this.setData({ currentView: view })
    
    if (view === 'history') {
      this.loadAnswerLocks()
    }
  },

  // 显示创建模态框
  onShowCreateModal() {
    this.setData({ 
      showCreateModal: true,
      createForm: {
        question: '',
        answer: '',
        hint: '',
        difficulty: 'medium',
        category: 'personal',
        isPrivate: false,
        unlockCondition: 'correct_answer'
      }
    })
  },

  // 创建表单输入
  onCreateFormInput(e) {
    const { field } = e.currentTarget.dataset
    const { value } = e.detail
    
    this.setData({
      [`createForm.${field}`]: value
    })
  },

  // 选择难度
  onSelectDifficulty(e) {
    const { difficulty } = e.currentTarget.dataset
    this.setData({
      'createForm.difficulty': difficulty
    })
  },

  // 选择分类
  onSelectCategory(e) {
    const { category } = e.currentTarget.dataset
    this.setData({
      'createForm.category': category
    })
  },

  // 切换私密性
  onTogglePrivate() {
    this.setData({
      'createForm.isPrivate': !this.data.createForm.isPrivate
    })
  },

  // 创建答案锁
  async onCreateLock() {
    const { question, answer, hint, difficulty, category, isPrivate, unlockCondition } = this.data.createForm
    
    if (!question.trim()) {
      wx.showToast({
        title: '请输入问题',
        icon: 'error'
      })
      return
    }
    
    if (!answer.trim()) {
      wx.showToast({
        title: '请输入答案',
        icon: 'error'
      })
      return
    }
    
    try {
      const newLock = {
        id: Date.now().toString(),
        question: question.trim(),
        answer: answer.trim(),
        hint: hint.trim(),
        difficulty,
        category,
        isPrivate,
        unlockCondition,
        createdAt: new Date().toISOString(),
        createdBy: app.globalData.userInfo?.id || 'anonymous',
        isUnlocked: false,
        unlockedAt: null,
        unlockedBy: null,
        attempts: 0,
        maxAttempts: difficulty === 'easy' ? 5 : difficulty === 'medium' ? 3 : 2
      }
      
      const locks = storage.get('answer_locks') || []
      locks.unshift(newLock)
      storage.set('answer_locks', locks)
      
      this.setData({ 
        showCreateModal: false,
        currentView: 'history'
      })
      
      this.loadAnswerLocks()
      this.loadStats()
      
      wx.showToast({
        title: '创建成功',
        icon: 'success'
      })
      
      // 触觉反馈
      if (this.data.settings.soundEffects) {
        wx.vibrateShort()
      }
    } catch (error) {
      console.error('创建答案锁失败:', error)
      wx.showToast({
        title: '创建失败',
        icon: 'error'
      })
    }
  },

  // 打开解锁模态框
  onOpenUnlockModal(e) {
    const { lockId } = e.currentTarget.dataset
    const lock = this.data.answerLocks.find(l => l.id === lockId)
    
    if (!lock) return
    
    if (lock.isUnlocked) {
      this.openLockDetail(lockId)
      return
    }
    
    this.setData({
      currentLock: lock,
      showUnlockModal: true,
      unlockForm: {
        userAnswer: '',
        attempts: lock.attempts || 0,
        maxAttempts: lock.maxAttempts || 3,
        showHint: false,
        isUnlocked: false
      }
    })
  },

  // 解锁表单输入
  onUnlockFormInput(e) {
    const { value } = e.detail
    this.setData({
      'unlockForm.userAnswer': value
    })
  },

  // 显示提示
  onShowHint() {
    this.setData({
      'unlockForm.showHint': true
    })
  },

  // 尝试解锁
  async onAttemptUnlock() {
    const { currentLock, unlockForm } = this.data
    const { userAnswer } = unlockForm
    
    if (!userAnswer.trim()) {
      wx.showToast({
        title: '请输入答案',
        icon: 'error'
      })
      return
    }
    
    const isCorrect = userAnswer.trim().toLowerCase() === currentLock.answer.toLowerCase()
    const newAttempts = unlockForm.attempts + 1
    
    if (isCorrect) {
      // 解锁成功
      await this.unlockSuccess(currentLock)
    } else {
      // 解锁失败
      if (newAttempts >= unlockForm.maxAttempts) {
        // 达到最大尝试次数
        this.unlockFailed(currentLock, newAttempts)
      } else {
        // 继续尝试
        this.setData({
          'unlockForm.attempts': newAttempts,
          'unlockForm.userAnswer': ''
        })
        
        wx.showToast({
          title: `答案错误，还有${unlockForm.maxAttempts - newAttempts}次机会`,
          icon: 'error'
        })
      }
    }
  },

  // 解锁成功
  async unlockSuccess(lock) {
    try {
      const locks = storage.get('answer_locks') || []
      const lockIndex = locks.findIndex(l => l.id === lock.id)
      
      if (lockIndex !== -1) {
        locks[lockIndex] = {
          ...locks[lockIndex],
          isUnlocked: true,
          unlockedAt: new Date().toISOString(),
          unlockedBy: app.globalData.userInfo?.id || 'anonymous',
          attempts: this.data.unlockForm.attempts + 1
        }
        
        storage.set('answer_locks', locks)
      }
      
      this.setData({
        showUnlockModal: false,
        'unlockForm.isUnlocked': true
      })
      
      this.loadAnswerLocks()
      this.loadStats()
      
      // 显示成功动画
      wx.showToast({
        title: '解锁成功！',
        icon: 'success'
      })
      
      // 触觉反馈
      if (this.data.settings.soundEffects) {
        wx.vibrateShort()
      }
      
      // 延迟显示详情
      setTimeout(() => {
        this.openLockDetail(lock.id)
      }, 1500)
    } catch (error) {
      console.error('解锁失败:', error)
      wx.showToast({
        title: '解锁失败',
        icon: 'error'
      })
    }
  },

  // 解锁失败
  unlockFailed(lock, attempts) {
    try {
      const locks = storage.get('answer_locks') || []
      const lockIndex = locks.findIndex(l => l.id === lock.id)
      
      if (lockIndex !== -1) {
        locks[lockIndex] = {
          ...locks[lockIndex],
          attempts
        }
        
        storage.set('answer_locks', locks)
      }
      
      this.setData({ showUnlockModal: false })
      
      wx.showModal({
        title: '解锁失败',
        content: '已达到最大尝试次数，请稍后再试或寻求提示',
        showCancel: false
      })
    } catch (error) {
      console.error('更新尝试次数失败:', error)
    }
  },

  // 打开锁详情
  openLockDetail(lockId) {
    const locks = storage.get('answer_locks') || []
    const lock = locks.find(l => l.id === lockId)
    
    if (lock) {
      this.setData({
        currentLock: lock,
        showDetailModal: true
      })
    }
  },

  // 删除答案锁
  onDeleteLock(e) {
    const { lockId } = e.currentTarget.dataset
    
    wx.showModal({
      title: '确认删除',
      content: '删除后无法恢复，确定要删除这个答案锁吗？',
      success: (res) => {
        if (res.confirm) {
          this.deleteLock(lockId)
        }
      }
    })
  },

  // 执行删除
  deleteLock(lockId) {
    try {
      const locks = storage.get('answer_locks') || []
      const filteredLocks = locks.filter(lock => lock.id !== lockId)
      
      storage.set('answer_locks', filteredLocks)
      
      this.loadAnswerLocks()
      this.loadStats()
      
      wx.showToast({
        title: '删除成功',
        icon: 'success'
      })
    } catch (error) {
      console.error('删除失败:', error)
      wx.showToast({
        title: '删除失败',
        icon: 'error'
      })
    }
  },

  // 过滤选项变化
  onFilterChange(e) {
    const { type, value } = e.currentTarget.dataset
    
    this.setData({
      [`filterOptions.${type}`]: value
    })
    
    this.loadAnswerLocks()
  },

  // 显示统计模态框
  onShowStatsModal() {
    this.setData({ showStatsModal: true })
  },

  // 显示设置模态框
  onShowSettingsModal() {
    this.setData({ showSettingsModal: true })
  },

  // 切换设置
  onToggleSetting(e) {
    const { setting } = e.currentTarget.dataset
    const newValue = !this.data.settings[setting]
    
    this.setData({
      [`settings.${setting}`]: newValue
    })
    
    this.saveSettings()
  },

  // 保存设置
  saveSettings() {
    storage.set('final_answer_settings', this.data.settings)
  },

  // 关闭模态框
  onCloseModal() {
    this.setData({
      showCreateModal: false,
      showUnlockModal: false,
      showStatsModal: false,
      showDetailModal: false,
      showSettingsModal: false,
      currentLock: null
    })
  },

  // 分享答案锁
  onShareLock(e) {
    const { lockId } = e.currentTarget.dataset
    const lock = this.data.answerLocks.find(l => l.id === lockId)
    
    if (!lock) return
    
    return {
      title: `来解锁我的问题：${lock.question}`,
      path: `/pages/final-answer/index?lockId=${lockId}`,
      imageUrl: '/images/share-lock.png'
    }
  },

  // 获取难度文本
  getDifficultyText(difficulty) {
    const difficultyMap = {
      easy: '简单',
      medium: '中等', 
      hard: '困难'
    }
    return difficultyMap[difficulty] || '未知'
  },

  // 获取分类文本
  getCategoryText(categoryId) {
    const category = this.data.categories.find(cat => cat.id === categoryId)
    return category ? category.name : '未知分类'
  },

  // 获取分类信息的辅助方法
  getCategoryInfo(categoryId) {
    return this.data.categories.find(cat => cat.id === categoryId) || { icon: '❓', name: '未知', color: '#999999' }
  },

  // 获取难度信息的辅助方法
  getDifficultyInfo(difficultyId) {
    return this.data.difficulties.find(diff => diff.id === difficultyId) || { name: '未知', color: '#999999' }
  },

  // 格式化时间
  formatTime(dateString) {
    const date = new Date(dateString)
    const now = new Date()
    const diff = now - date
    
    const minutes = Math.floor(diff / (1000 * 60))
    const hours = Math.floor(diff / (1000 * 60 * 60))
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))
    
    if (minutes < 1) return '刚刚'
    if (minutes < 60) return `${minutes}分钟前`
    if (hours < 24) return `${hours}小时前`
    if (days < 7) return `${days}天前`
    
    return date.toLocaleDateString()
  },

  // 分享应用
  onShareAppMessage() {
    return {
      title: 'LAgain - 最终答案之锁，解锁彼此的心',
      path: '/pages/final-answer/index',
      imageUrl: '/images/share-final-answer.png'
    }
  }
})